/*******************************************************************************
 * Package: com.song.rabbit.mq.callback
 * Type:    RabbitMqCallback
 * Date:    2023-05-21 12:05
 *
 * Copyright (c) 2023 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.rabbit.mq.callback;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 功能描述：消息可靠抵达
 *
 * @author Songxianyang
 * @date 2023-05-21 12:05
 */
@Configuration
@Slf4j
public class RabbitMqCallback {
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private MyConfirmCallback myConfirmCallback;
    /**
     * 生产者生产消息后抵达消息中间件就会调用
     * ConfirmCallback回调函数：
     * 抵达mq
     * Confirmation callback.
     *  correlationData 回调的相关数据。
     *  ack 对于 ack，对于 nack 为假
     *  cause 失败原因，对于 nack，如果可用，否则为 null。
     *
     */
    @PostConstruct
    public void arriveMqCallback(){

        // 设置回调
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            log.info("correlationData消息唯一id>>>>>{}",correlationData.getId());
            // todo
            //log.info("correlationData返回的消息数据>>>>>{}",correlationData.getReturned());
            //log.info("correlationData返回的消息数据>>>>>{}",correlationData.getReturned());
            log.info("ack是否抵达成功>>>>>{}",ack);
            log.info("cause失败原因，成功则返回null>>>>>{}",cause);
        });
    }

    /**
     * 交换机到达---->队列
     * 由于某些原因未将消息传送到指定的队列时，触发的回调函数
     */
    @PostConstruct
    public void exchangeArriveQueue() {
        // todo
        //rabbitTemplate.setReturnsCallback(returned -> {
        //    log.info("交换机：》》》》{}", returned.getExchange());
        //    log.info("投递失败的消息内容：》》》》{}", returned.getMessage());
        //    log.info("状态码：》》》》{}", returned.getReplyCode());
        //    log.info("失败的原因：》》》》{}", returned.getReplyText());
        //    log.info("路由键：》》》》{}", returned.getRoutingKey());
        //});

    }

}
